package com.yq.interview.study.thread;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName DeadLockDemo
 * @Description TODO
 * @Author yaoqiang
 * @Date 2020/11/24 11:01
 * @Version 1.0
 */
public class DeadLockDemo {
    public static void main(String[] args) {

        String lockA="lockA";
        String lockB="lockB";

        //线程操纵资源类
        new Thread(new HoldLock(lockA,lockB),"t1").start();
        new Thread(new HoldLock(lockB,lockA),"t2").start();
        /***
         * win下的类似ps的命令，我们只查java，所以有jps 命令jsp -l
         * 9636的进程号
         * jstack 9636 ：发现是found 1 deadLock
         */
    }
}

class HoldLock implements  Runnable{
    private String lockA;
    private String lockB;

    public HoldLock(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName()+"自己持有"+lockA+"尝试获取"+lockB);
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
            synchronized (lockB){
                System.out.println(Thread.currentThread().getName()+"自己持有"+lockB+"尝试获取"+lockA);
            }
        }
    }
}